<?php
/**
 * Created by PhpStorm.
 * User: cc
 * Date: 2021/10/9
 * Time: 5:49 下午
 */

namespace app\common\cachemodel\live;

use app\chat\LiveMessage as CharLiveMessage;
use app\common\lib\Util;
use app\common\model\BaseCache;
use app\common\model\User;
use think\Log;
use XznsTools\cache\CacheManage;

/**
 * Class LiveOrderData
 * @package app\common\cachemodel\live
 */
class LiveOrderData extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.live_order_data';
    protected $cacheModel = 'live.live_order';

    /**
     * 添加直播间下单数据
     * @param $orders
     * @return bool
     */
    public function saveData($orders)
    {
        try
        {
            $num = count($orders);
            //增加直播间数据统计记录
            $liveData = [];
            $liveInfo = [];
            $uid = 0;
            $lcName = '';
            $lcGname = '';
            $lcPrice = 0;
            $liveRecordId = 0;
            $totalPrice = 0;
            $discountPercent = 0;
            $orderId = '';

            //计算商品优惠券折扣力度
            foreach ($orders as $k => $item)
            {
                $orderId = $item['order_id'];
                //若订单是内部vip则不记录直播间
                if (!in_array($item['order_type'], [14, 15, 19, 20, 21], false))
                {
                    //获取当前用户的内部VIP登等级
                    $vipLevel = Util::getVips($item['uid'], $item['order_type'], $item['rid']);
                    if ($vipLevel && $item['total_amount'] <= 0.01)
                    {
                        return true;
                    }
                }
                $extend = $item['extend'] ? json_decode($item['extend'], true) : [];
                if (isset($extend['coupon']['discount_price']))
                {
                    $couponDiscount = $extend['coupon']['discount_price'];//总优惠券折扣
                    $totalPrice = $item['total_amount'];//订单总金额(已去除活动折扣)
                }
            }
            if (isset($couponDiscount))
            {
                $discountPercent = $couponDiscount / ($totalPrice + $couponDiscount);//总优惠券折扣力度
            }

            //组合直播间订单
            foreach ($orders as $k => $item)
            {
                $extend = $item['extend'] ? json_decode($item['extend'], true) : [];
                if (isset($extend['live_info']))
                {
                    //获取直播商品推荐活动信息
                    $gid = !empty($item['gids']) ? $item['gids'] : $item['gid'];
                    $liveRecordId = $extend['live_info']['live_record_id'];

                    //有活动的商品
                    if (isset($extend['new_active'][$gid]['ac_id']))
                    {
                        $active = (new LiveGoodsActivity())->getInfoById($extend['new_active'][$gid]['ac_id']);
                        $price = $extend['new_active'][$gid]['price'];//单价(已去除活动折扣)
                        $discount = $extend['new_active'][$gid]['discount_price'];//单价活动折扣金额
                        $priceDiscount = $price * $discountPercent;//单价优惠券折扣

                        $resPrice = $price - $priceDiscount;
                        $resDiscount = $discount + $priceDiscount;
                    } else//无活动的商品
                    {
                        $active = [];
                        $price = $extend['goods_info'][$gid]['price'] ?? ($item['total_amount'] / $num);//单价
                        $discount = 0;//单价活动折扣
                        $priceDiscount = $price * $discountPercent;//单价优惠券折扣

                        $resPrice = $price - $priceDiscount;
                        $resDiscount = $discount + $priceDiscount;

                    }


                    $liveData[] = [
                        'live_id' => $extend['live_info']['live_id'],
                        'live_record_id' => $extend['live_info']['live_record_id'],
                        'active_name' => $active['name'] ?? '',
                        'order_type' => $item['order_type'],
                        'gid' => $gid,
                        'num' => $extend['goods_info'][$gid]['num'] ?? 1,
                        'price' => $resPrice,
                        'discount' => $resDiscount,
                        'order_num' => $item['order_id'],
                        'create_time' => time()
                    ];
                    $liveInfo = $extend['live_info'];
                    $uid = $item['uid'];
                    if (isset($extend['new_active'][$gid]['name']))
                    {
                        $lcName = $extend['new_active'][$gid]['name'];
                        $lcGname .= $extend['new_active'][$gid]['gname'] . '、';
                        $lcPrice += $resPrice * $extend['new_active'][$gid]['num'];
                    }
                }
            }

            $this->insertAll($liveData);

            //给主播端和后台发送socket
            if (!empty($liveInfo))
            {
                $userInfo = (new User())->getUserinfo(['id' => $uid]);
                //向所有人发送消息
                $lcName = $lcName ?: '原价';
                $lcGname = $lcGname ? trim($lcGname, '、') : $liveInfo['gname'];
                $lcPrice = $lcPrice ?: $liveInfo['total_amount'];
                $username = $userInfo['nickname'];
//                $wsContent = "{$username}购买了：{$lcGname} - {$lcName}{$lcPrice}";
                $wsContent = "{$username}购买了：{$lcGname} - {$lcPrice}元";
                $wsData = [
                    'msg_info' => [
                        'color' => '#FFB500',
                        'content' => $wsContent,
                        'id' => 0
                    ],
                    'user_info' => null
                ];
                Log::write('发送直播间下单WS消息:' . json_encode($wsData, JSON_UNESCAPED_UNICODE) . "，直播间ID：{$liveInfo['live_id']}，UID：{$uid}，order_id：{$orderId}", 'log', true);
                CharLiveMessage::sendMsg(CharLiveMessage::who(CharLiveMessage::WHO_TYPE_LIVER, $liveInfo['live_id'], $liveInfo['live_id']), CharLiveMessage::MSG_TYPE_POP_MSG_LIVER_ORDER, $wsData);

                //临时记录直播间下单用
                $liveTmpOrderUid = [$uid => time()];
                CacheManage::getInstance()->setCacheConfig($this->cacheModel, $liveRecordId)->ZsAddIocData($liveTmpOrderUid, 'list', function () use ($liveTmpOrderUid)
                {
                    return $liveTmpOrderUid;
                });
            }
        }
        catch (\Exception $e)
        {
            Log::write('直播间订单记录失败:' . $e->getMessage() . '文件信息:[' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return false;
        }
        return true;
    }

    /**
     * 获取当前直播记录 中 下单的用户 uid
     * @param $liveRecordId
     * @return array|mixed
     * @throws \Exception
     */
    public function getLiveRecordOrderUid($liveRecordId)
    {
        $resData = CacheManage::getInstance()->setCacheConfig($this->cacheModel, $liveRecordId)->ZsGetIocData('list', function ()
        {
            return [];
        });

        return $resData;
    }


    /**
     * 获取
     * @param $liveRecordIds
     * @return array
     */
    public function getLiveRecordOrderData($liveRecordIds)
    {
        $data = $this->whereIn('live_record_id', $liveRecordIds)->column('active_name,order_type,gid,num,price,discount', 'id');

        $resData = [];
        foreach ($data as $datum)
        {
            switch ($datum['order_type'])
            {
                case 14:
                    $num = $resData['mall_goods'][$datum['gid']]['num'] ?? 0;
                    $resData['mall_goods'][$datum['gid']] = [
                        'gid' => $datum['gid'],
                        'num' => $num + $datum['num'],
                        'order_type' => 14,
                        'name' => $datum['active_name'],
                    ];

                    $resData['mall_goods_price'] = [
                        'price' => ($resData['mall_goods_price']['price'] ?? 0) + ($datum['price'] * $datum['num']),
                        'discount' => ($resData['mall_goods_price']['discount'] ?? 0) + ($datum['discount'] * $datum['num'])
                    ];
                    break;
                case 19:
                    $num = $resData['astro_goods'][$datum['gid']]['num'] ?? 0;
                    $resData['astro_goods'][$datum['gid']] = [
                        'gid' => $datum['gid'],
                        'order_type' => (int)$datum['order_type'],
                        'num' => $num + $datum['num'],
                    ];

                    $resData['astro_goods_price'] = [
                        'price' => ($resData['astro_goods_price']['price'] ?? 0) + ($datum['price'] * $datum['num']),
                        'discount' => ($resData['astro_goods_price']['discount'] ?? 0) + ($datum['discount'] * $datum['num']),
                        'unit_price' => $datum['price'],
                        'total_num' => ($resData['astro_goods_price']['total_num'] ?? 0) + $datum['num'],
                    ];
                    break;
                case 20:
                    $num = $resData['dice_goods'][$datum['gid']]['num'] ?? 0;
                    $resData['dice_goods'][$datum['gid']] = [
                        'gid' => $datum['gid'],
                        'order_type' => (int)$datum['order_type'],
                        'num' => $num + $datum['num'],
                    ];

                    $resData['dice_goods_price'] = [
                        'price' => ($resData['dice_goods_price']['price'] ?? 0) + ($datum['price'] * $datum['num']),
                        'discount' => ($resData['dice_goods_price']['discount'] ?? 0) + ($datum['discount'] * $datum['num']),
                        'unit_price' => $datum['price'],
                        'total_num' => ($resData['dice_goods_price']['total_num'] ?? 0) + $datum['num'],
                    ];
                    break;
                case 21:
                    $num = $resData['tarot_goods'][$datum['gid']]['num'] ?? 0;
                    $resData['tarot_goods'][$datum['gid']] = [
                        'gid' => $datum['gid'],
                        'order_type' => (int)$datum['order_type'],
                        'num' => $num + $datum['num'],
                    ];

                    $resData['tarot_goods_price'] = [
                        'price' => ($resData['tarot_goods_price']['price'] ?? 0) + ($datum['price'] * $datum['num']),
                        'discount' => ($resData['tarot_goods_price']['discount'] ?? 0) + ($datum['discount'] * $datum['num']),
                        'unit_price' => $datum['price'],
                        'total_num' => ($resData['tarot_goods_price']['total_num'] ?? 0) + $datum['num'],
                    ];
                    break;
                default:
                    $num = $resData['goods'][$datum['gid']]['num'] ?? 0;
                    $resData['goods'][$datum['gid']] = [
                        'gid' => $datum['gid'],
                        'order_type' => (int)$datum['order_type'],
                        'num' => $num + $datum['num'],
                    ];

                    $resData['goods_price'] = [
                        'price' => ($resData['goods_price']['price'] ?? 0) + ($datum['price'] * $datum['num']),
                        'discount' => ($resData['goods_price']['discount'] ?? 0) + ($datum['discount'] * $datum['num'])
                    ];
            }
        }

        $goodIds = isset($resData['goods']) ? array_keys($resData['goods']) : [];

        if ($goodIds)
        {
            $goodsInfo = $this->table('wechat_backup_07_18_14_43_00.app_goods')->whereIn('id', $goodIds)->column('name', 'id');

            foreach ($resData['goods'] as $gid => $resDatum)
            {
                $resData['goods'][$gid]['name'] = $goodsInfo[$gid] ?? '';
            }
        }

        $mallGoodIds = isset($resData['mall_goods']) ? array_keys($resData['mall_goods']) : [];

        if ($mallGoodIds)
        {
            $mallGoodIds = !is_array($mallGoodIds) ? [$mallGoodIds] : $mallGoodIds;

            $goodsInfo = $this->table('wechat_backup_07_18_14_43_00.mall_goods_attr')->whereIn('id', $mallGoodIds)->column('name', 'id');

            foreach ($resData['mall_goods'] as $gid => $resDatum)
            {
                if (isset($goodsInfo[$gid]))
                {
                    $resData['mall_goods'][$gid]['name'] = $resData['mall_goods'][$gid]['name'] . '-' . $goodsInfo[$gid];
                }
            }
        }

        return $resData;
    }

    /**
     * 获取时间范围内的订单数据
     * @param $liveId
     * @param $startTime
     * @param $endTIme
     * @return array
     */
    public function getTimeRangeOrderData($liveId, $startTime, $endTIme)
    {
        $data = $this->where(['live_id' => $liveId])->where('create_time', 'between time', [$startTime, $endTIme])->column('order_type,gid,num,price,discount', 'id');

        $resData = [];
        foreach ($data as $datum)
        {
            if ($datum['order_type'] == 14)
            {
                $num = $resData['mall_goods'][$datum['gid']]['num'] ?? 0;
                $resData['mall_goods'][$datum['gid']] = [
                    'gid' => $datum['gid'],
                    'num' => $num + $datum['num'],
                ];

                $resData['mall_goods_price'] = [
                    'price' => ($resData['mall_goods_price']['price'] ?? 0) + ($datum['price'] * $datum['num']),
                    'discount' => ($resData['mall_goods_price']['discount'] ?? 0) + ($datum['discount'] * $datum['num'])
                ];
            } else
            {
                $num = $resData['goods'][$datum['gid']]['num'] ?? 0;
                $resData['goods'][$datum['gid']] = [
                    'gid' => $datum['gid'],
                    'num' => $num + $datum['num'],
                ];

                $resData['goods_price'] = [
                    'price' => ($resData['goods_price']['price'] ?? 0) + ($datum['price'] * $datum['num']),
                    'discount' => ($resData['goods_price']['discount'] ?? 0) + ($datum['discount'] * $datum['num'])
                ];
            }
        }

        $goodIds = isset($resData['goods']) ? array_keys($resData['goods']) : [];

        if ($goodIds)
        {
            $goodsInfo = $this->table('wechat_backup_07_18_14_43_00.app_goods')->whereIn('id', $goodIds)->column('name', 'id');

            foreach ($resData['goods'] as $gid => $resDatum)
            {
                $resData['goods'][$gid]['name'] = $goodsInfo[$gid] ?? '';
            }
        }

        $mallGoodIds = isset($resData['mall_goods']) ? array_keys($resData['mall_goods']) : [];

        if ($mallGoodIds)
        {
            $goodsInfo = $this->table('wechat_backup_07_18_14_43_00.mall_goods_attr')->whereIn('id', $goodIds)->column('name', 'id');

            foreach ($resData['mall_goods'] as $gid => $resDatum)
            {
                $resData['mall_goods'][$gid]['name'] = $goodsInfo[$gid] ?? '';
            }
        }

        return $resData;
    }
}
